//和用户相关的状态管理

import { createSlice } from "@reduxjs/toolkit";
// import { request } from "@/utils";
import { Dispatch } from "redux";
import { setToken as _setToken, getToken, removeToken } from "../../utils";
import { type LoginForm, loginAPI, getProfileAPI } from "../../apis/user";

interface UserState {
  token: string;
  userInfo: UserInfo;
}

interface UserInfo {
  id: string;
  photo: string;
  name: string;
  mobile: string;
  gender: number;
  birthday: string;
}

const userStore = createSlice({
  name: "user",
  initialState: {
    token: getToken() || "",
    userInfo: {},
  } as UserState,
  reducers: {
    setToken(state: UserState, action: { payload: string }) {
      state.token = action.payload;
      _setToken(action.payload);
    },
    setUserInfo(state: UserState, action: { payload: UserInfo }) {
      state.userInfo = action.payload;
    },
    clearUserInfo(state: UserState) {
      state.token = "";
      state.userInfo = {} as UserInfo;
      _setToken("");
      removeToken();
    },
  },
});

//解构出actionCreater
const { setToken, setUserInfo, clearUserInfo } = userStore.actions;

//获取reducer函数
const userReducer = userStore.reducer;

const fetchLogin = (loginForm: LoginForm) => {
  return async (dispatch: Dispatch) => {
    const res = await loginAPI(loginForm);
    dispatch(setToken(res.data.token));
  };
};

// 获取个人用户信息异步方法
const fetchUserInfo = () => {
  return async (dispatch: Dispatch) => {
    const res = await getProfileAPI();
    dispatch(setUserInfo(res.data));
  };
};

export { fetchLogin, fetchUserInfo, setToken, clearUserInfo };
export default userReducer;
